package com.mamba.microservice.dubbo.filter;

import com.mamba.microservice.context.ContextLogbackUtils;
import com.mamba.microservice.context.ServiceContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import java.util.Map;

/**
 * Copyright ©2020 360jinrong All Rights Reserved
 * 请添加类/接口的说明：初始化服务提供端的上下文信息
 *
 * @Package: com.mamba.microservice.dubbo.filter
 * @author: fangjin
 * @date: 2020年04月22日 10时25分
 */
@Slf4j
@Activate(group = {CommonConstants.PROVIDER}, order = -6000)
public class MmsProviderContextFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        ServiceContext serviceContext = ServiceContext.getContext();
        try {
            serviceContext.clearContextVariables();
            /** 接收传来的请求号*/
            Map<String, String> attachments = RpcContext.getContext().getAttachments();
            serviceContext.setContextVariables(attachments);
            String requestNo = serviceContext.getRequestNo();
            if (StringUtils.isEmpty(requestNo)) {
                log.debug("沒有收到requestNo");
            }
            ContextLogbackUtils.addContext2MDC();
            return invoker.invoke(invocation);
        } catch (Exception e) {
            throw e;
        } finally {
            serviceContext.clearContextVariables();
            ContextLogbackUtils.removeContextFromMDC();
        }
    }

    @Override
    public Result onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
        return null;
    }
}
